from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from .. import models
from django.core.urlresolvers import reverse


# Create your views here.

# 商品分类添加
def cateadd(request):
    # 判断请求方式
    if request.method =='GET':
        # 获取全部分类
        data = models.category.objects.extra(select={'paths':'concat(path,id)'}).order_by('paths')
        # 分配数据
        context = {'categorylist':data}
        # 加载模板
        return render(request,'myadmin/category/add.html',context)

    elif request.method =='POST':
        try:
            # 执行添加
            ob = models.category()
            ob.pid = request.POST.get('pid')
            ob.name = request.POST.get('name')

            # 判断是否为顶级分类
            if ob.pid =='0':
                ob.path = '0,'
            else:
                # 获取当前所选分类 path
                fob = models.category.objects.get(id=request.POST.get('pid'))
                ob.path = fob.path+ob.pid+','
                print(ob.pid, ob.name, ob.path)
            ob.save()
            # print(ob.pid, ob.name,ob.path)
            return HttpResponse('<script>alert("添加成功");location.href="' + reverse('myadmin_cate_index') + '"</script>')
        except:
            return HttpResponse('<script>alert("添加失败");location.href="' + reverse('myadmin_cate_add') + '"</script>')



# 商品分类 列表页
def cateindex(request):
    data = models.category.objects.extra(select={'paths': 'concat(path,id)'}).order_by('paths')
    num = data.count()
    # 获取搜索参数 并判断是否有值
    types = request.GET.get('types')
    keywords = request.GET.get('keywords')

    #数据分页
    from django.core.paginator import Paginator

    if  keywords:
        data = data.filter(name__contains=keywords)

    # 实例化分页类 参数1,获取的所有的数据对象   参数2 每页显示多少条
    paginator = Paginator(data, 10)

    # 获取当前页码数  ?p=n
    p = request.GET.get('p', 1)

    # 获取当前页的数据
    categorylist = paginator.page(p)

    # 分配数据
    context = {'categorylist': categorylist}

    return render(request,'myadmin/category/index.html',context)

# 商品分类 删除
def catedel(request):
    # 接收请求参数
    cid = request.GET.get('id')
    # 判断当前类 是否有子类
    num = models.category.objects.filter(pid=cid).count()
    # 没有子类
    if num ==0:
        #获取分类对象并删除数据
        ob = models.category.objects.get(id=cid)
        ob.delete()
        print(cid)
        return JsonResponse({'error':0,'msg':'删除成功'})
    # 有子类
    else:
        return JsonResponse({'error': 1, 'msg': '当前类名下还有子类,不能删除'})

# 商品分类 修改
def cateedit(request):
    try:
        # 根据请求参数获取分类对象
        ob = models.category.objects.get(id=request.GET.get('id'))
        print(ob)
        #修改分类名称
        ob.name = request.GET.get('name')

        ob.save()
        return JsonResponse({'error':0,'msg':'修改成功'})
    except:
        return JsonResponse({'error': 1, 'msg': '修改失败'})